package com.budwk.app.util.poiUtils;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.policy.PictureRenderPolicy;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.getTemplatePathByOS;

/**
 * @author yangweimin
 * @project wk-mini
 * @description 威清门图片生成
 * @date 2023/10/14 00:26:53
 */
public class WeiQingMenPictureUtils {

    public static ByteArrayOutputStream getByteArrayOutputStream(String title, List<String> urls, String templateName) {
        ByteArrayOutputStream wordOutPutStream = new ByteArrayOutputStream();
        Map<String, Object> datas = new HashMap<>();
        datas.put("title", title);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<String> pictureTag = new ArrayList<>();
        for (String url : urls) {
            Map<String, Object> detailMap = new HashMap<String, Object>();//将word中标签名的例和对应数据保存到map
            detailMap.put("picture", CommonFormOfficeUtils.addWordPicture(url, 10F));
            pictureTag.add("picture");//用于设置图片
            list.add(detailMap);//将设置好的行保存到list集合中
        }
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder().bind("pictures", policy).build();//设置列表配置，如果有多个列表时需加.bind("list1", policy) 新列表配置即可
        for (String tag:pictureTag) {
            config.customPolicy(tag,new PictureRenderPolicy());//设置图片，不然保存的是一串字符
        }
        //将列表保存到渲染的map中
        datas.put("pictures", list);
        //获取模板
        String filePathStr = getTemplatePathByOS(templateName);
        //3.创建XWPFTemplate对象，并设置读取模板路径和要渲染的数据
        XWPFTemplate template = XWPFTemplate.compile(filePathStr, config).render(datas);
        try {
            template.write(wordOutPutStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wordOutPutStream;
    }
}
